package org.xx.armory.spring5.mvc;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于简化请求URL的拦截器。
 *
 * <ul>
 *     <li>{@literal /*&#42;/index} 被重写为 {@literal /*&#42;/}</li>
 *     <li>{@literal /*&#42;/index(args)} 被重写为 {@literal /*&#42;/(args)}</li>
 * </ul>
 */
public class RewriteSimpleURLInterceptor
        implements HandlerInterceptor {
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler
    )
            throws Exception {
        final var url = request.getRequestURI();
        final var p0 = url.lastIndexOf('?');
        var s0 = p0 > 0 ? url.substring(0, p0) : url;
        final var p1 = url.lastIndexOf('/');
        s0 = s0.substring(p1);
        if ("/index".equals(s0) || (s0.startsWith("/index(") && s0.endsWith(")"))) {
            response.sendRedirect("./");
            return false;
        }
        return true;
    }
}
